package com.accounting.juanjuan.interceptor;

import com.accounting.juanjuan.constant.PathConstant;
import com.accounting.juanjuan.utils.ActionUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * 路径拦截器
 *
 * @Author xxj
 * @Date 2024/1/27 22:49
 * @Version 1.0
 */
@Component
public class PathInterceptor implements HandlerInterceptor {
    /**
     * preHandle()是Controller方法调用前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //这里是判断，使用方是否是可以允许的域名
        Enumeration<String> headers = request.getHeaders(PathConstant.HOST);
        String remoteHost = "";
        if(headers.hasMoreElements()){
            remoteHost = headers.nextElement();
        }
        if (PathConstant.ALLOWED_HOST.equals(remoteHost)) {
            return true;
        }
        ActionUtil.writeStreamToResponseByError(response, "不允许访问！");
        return false;
    }
}
